#!/bin/bash
#---
IP(){
    echo "Input router IP:"
    read ip
    while [ true ]
    do
        if [ ! `echo $ip|grep "^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$"` ];then
            echo "\
Wrong format!!!   input again: \
格式不对！！！请重新输入： \
"
            IP
        else
            break
        fi
    done
}

MIN(){
    echo "Input sleep minite:"
    read min
    while true
    do
        if [ ! `echo $min|grep "^[0-9]*$"` ];then
            echo "\
Wrong format!!!   input again: \
格式不对！！！请重新输入： \
                "
            MIN
        else
            break
        fi
    done
}

COUNT(){
    echo "Input check cycle count:"
    read count
    while true
    do
        if [ ! `echo $count|grep "^[0-9]*$"` ];then
            echo "\
Wrong format!!!   input again: \
格式不对！！！请重新输入： \
                "
            COUNT
        elif [ $count -lt 3 ];then
            echo "Must more then 3.Input again: \
该值必须大于3，请重新输入："
            COUNT
        else
            break
        fi
    done
}
main(){
    echo "Current config:"
    echo `cat fakeUpsShutdown|grep "^IP"`
    echo `cat fakeUpsShutdown|grep "^min"`
    echo `cat fakeUpsShutdown|grep "^count"`
    echo "-----------------"
    echo "Please choose:"
    echo "1 ) Install"
    echo "2 ) Uninstall"
    echo "q ) Quit"
    echo "Type word and press enter:"
    read x
    case $x in
        1 )
            echo "Installing..."
            IP
            MIN
            COUNT
            if [[ $ip && $min && $count ]];then
                sed -i 's/^IP.*$/IP='$ip'/g' fakeUpsShutdown
                sed -i 's/^min.*$/min='$min'/g' fakeUpsShutdown
                sed -i 's/^count.*$/count='$count'/g' fakeUpsShutdown
                sed -i '/fakeUpsShutdown/d' /etc/crontab
                cp fakeUpsShutdown /sbin/fakeUpsShutdown
                chmod +x /sbin/fakeUpsShutdown
                echo "" >> /etc/crontab
                echo "@reboot root /sbin/fakeUpsShutdown > /dev/null" >> /etc/crontab
                systemctl restart cron
                killall fakeUpsShutdown > /dev/null
                nohup fakeUpsShutdown > /dev/null 2>&1 &
                echo "Install complete!"
                exit
            fi
            ;;
        2 )
            echo "Uninstalling..."
            rm /sbin/fakeUpsShutdown -rf
            sed -i '/fakeUpsShutdown/d' /etc/crontab
            systemctl restart cron
            killall fakeUpsShutdown > /dev/null
            echo "Uninstall complete!"
            exit
            ;;
        q )
            echo "Now quit."
            ;;
        * )
            echo "Please input right word."
            main
    esac
}

main
